from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.models import db
from app.models.user import User
from sqlalchemy import text
from datetime import datetime

dictionaries_bp = Blueprint('dictionaries', __name__)

@dictionaries_bp.route('/<dict_type>', methods=['GET'])
def get_dictionaries(dict_type):
    """获取指定类型的字典数据"""
    try:
        # 查询指定类型的字典数据
        query = text("""
            SELECT id, dict_type, dict_key, dict_label, dict_value, 
                   sort_order, is_active, is_system, parent_id, description
            FROM system_dictionaries 
            WHERE dict_type = :dict_type AND is_active = 1
            ORDER BY sort_order ASC, id ASC
        """)
        
        result = db.session.execute(query, {'dict_type': dict_type})
        dictionaries = []
        
        for row in result:
            dictionaries.append({
                'id': row.id,
                'dict_type': row.dict_type,
                'dict_key': row.dict_key,
                'dict_label': row.dict_label,
                'dict_value': row.dict_value,
                'sort_order': row.sort_order,
                'is_active': bool(row.is_active),
                'is_system': bool(row.is_system),
                'parent_id': row.parent_id,
                'description': row.description
            })
        
        return jsonify({
            'dictionaries': dictionaries,
            'total': len(dictionaries)
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@dictionaries_bp.route('/types', methods=['GET'])
def get_dictionary_types():
    """获取所有字典类型"""
    try:
        query = text("""
            SELECT DISTINCT dict_type, COUNT(*) as count
            FROM system_dictionaries 
            WHERE is_active = 1
            GROUP BY dict_type
            ORDER BY dict_type
        """)
        
        result = db.session.execute(query)
        types = []
        
        for row in result:
            types.append({
                'dict_type': row.dict_type,
                'count': row.count
            })
        
        return jsonify({'types': types}), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@dictionaries_bp.route('', methods=['GET'])
@jwt_required()
def get_all_dictionaries():
    """获取所有字典数据（管理员用）"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role != 'admin':
            return jsonify({'error': '权限不足'}), 403
        
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        dict_type = request.args.get('dict_type', '')
        search = request.args.get('search', '')
        
        # 构建查询条件
        conditions = []
        params = {}
        
        if dict_type:
            conditions.append('dict_type = :dict_type')
            params['dict_type'] = dict_type
        
        if search:
            conditions.append('(dict_key LIKE :search OR dict_label LIKE :search)')
            params['search'] = f'%{search}%'
        
        where_clause = 'WHERE ' + ' AND '.join(conditions) if conditions else ''
        
        # 查询总数
        count_query = text(f"""
            SELECT COUNT(*) as total
            FROM system_dictionaries 
            {where_clause}
        """)
        
        total_result = db.session.execute(count_query, params)
        total = total_result.scalar()
        
        # 查询数据
        offset = (page - 1) * per_page
        data_query = text(f"""
            SELECT id, dict_type, dict_key, dict_label, dict_value, 
                   sort_order, is_active, is_system, parent_id, description,
                   created_at, updated_at
            FROM system_dictionaries 
            {where_clause}
            ORDER BY dict_type, sort_order ASC, id ASC
            LIMIT :per_page OFFSET :offset
        """)
        
        params.update({'per_page': per_page, 'offset': offset})
        result = db.session.execute(data_query, params)
        
        dictionaries = []
        for row in result:
            dictionaries.append({
                'id': row.id,
                'dict_type': row.dict_type,
                'dict_key': row.dict_key,
                'dict_label': row.dict_label,
                'dict_value': row.dict_value,
                'sort_order': row.sort_order,
                'is_active': bool(row.is_active),
                'is_system': bool(row.is_system),
                'parent_id': row.parent_id,
                'description': row.description,
                'created_at': row.created_at.isoformat() if row.created_at else None,
                'updated_at': row.updated_at.isoformat() if row.updated_at else None
            })
        
        return jsonify({
            'dictionaries': dictionaries,
            'total': total,
            'page': page,
            'per_page': per_page,
            'pages': (total + per_page - 1) // per_page
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@dictionaries_bp.route('', methods=['POST'])
@jwt_required()
def create_dictionary():
    """创建字典项"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role != 'admin':
            return jsonify({'error': '权限不足'}), 403
        
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['dict_type', 'dict_key', 'dict_value', 'dict_label']
        for field in required_fields:
            if not data.get(field):
                return jsonify({'error': f'{field} 不能为空'}), 400
        
        # 检查是否已存在
        check_query = text("""
            SELECT COUNT(*) as count
            FROM system_dictionaries 
            WHERE dict_type = :dict_type AND dict_key = :dict_key
        """)
        
        result = db.session.execute(check_query, {
            'dict_type': data['dict_type'],
            'dict_key': data['dict_key']
        })
        
        if result.scalar() > 0:
            return jsonify({'error': '该字典项已存在'}), 400
        
        # 插入新字典项
        insert_query = text("""
            INSERT INTO system_dictionaries 
            (dict_type, dict_key, dict_label, dict_value, sort_order, 
             is_active, is_system, parent_id, description, created_at, updated_at)
            VALUES (:dict_type, :dict_key, :dict_label, :dict_value, :sort_order,
                    :is_active, :is_system, :parent_id, :description, :created_at, :updated_at)
        """)
        
        now = datetime.now()
        db.session.execute(insert_query, {
            'dict_type': data['dict_type'],
            'dict_key': data['dict_key'],
            'dict_label': data['dict_label'],
            'dict_value': data.get('dict_value'),
            'sort_order': data.get('sort_order', 0),
            'is_active': data.get('is_active', True),
            'is_system': data.get('is_system', False),
            'parent_id': data.get('parent_id'),
            'description': data.get('description'),
            'created_at': now,
            'updated_at': now
        })
        
        db.session.commit()
        
        return jsonify({'message': '字典项创建成功'}), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@dictionaries_bp.route('/<int:dict_id>', methods=['PUT'])
@jwt_required()
def update_dictionary(dict_id):
    """更新字典项"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role != 'admin':
            return jsonify({'error': '权限不足'}), 403
        
        data = request.get_json()
        
        # 检查字典项是否存在
        check_query = text("""
            SELECT is_system FROM system_dictionaries WHERE id = :id
        """)
        
        result = db.session.execute(check_query, {'id': dict_id})
        row = result.fetchone()
        
        if not row:
            return jsonify({'error': '字典项不存在'}), 404
        
        if row.is_system and not data.get('allow_system_edit', False):
            return jsonify({'error': '系统内置字典项不允许修改'}), 400
        
        # 构建更新字段
        update_fields = []
        params = {'id': dict_id, 'updated_at': datetime.now()}
        
        allowed_fields = ['dict_label', 'dict_value', 'sort_order', 'is_active', 'description']
        for field in allowed_fields:
            if field in data:
                update_fields.append(f'{field} = :{field}')
                params[field] = data[field]
        
        if not update_fields:
            return jsonify({'error': '没有可更新的字段'}), 400
        
        update_fields.append('updated_at = :updated_at')
        
        # 执行更新
        update_query = text(f"""
            UPDATE system_dictionaries 
            SET {', '.join(update_fields)}
            WHERE id = :id
        """)
        
        db.session.execute(update_query, params)
        db.session.commit()
        
        return jsonify({'message': '字典项更新成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@dictionaries_bp.route('/<int:dict_id>', methods=['DELETE'])
@jwt_required()
def delete_dictionary(dict_id):
    """删除字典项"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role != 'admin':
            return jsonify({'error': '权限不足'}), 403
        
        # 检查字典项是否存在且是否为系统内置
        check_query = text("""
            SELECT is_system FROM system_dictionaries WHERE id = :id
        """)
        
        result = db.session.execute(check_query, {'id': dict_id})
        row = result.fetchone()
        
        if not row:
            return jsonify({'error': '字典项不存在'}), 404
        
        if row.is_system:
            return jsonify({'error': '系统内置字典项不允许删除'}), 400
        
        # 删除字典项
        delete_query = text("""
            DELETE FROM system_dictionaries WHERE id = :id
        """)
        
        db.session.execute(delete_query, {'id': dict_id})
        db.session.commit()
        
        return jsonify({'message': '字典项删除成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@dictionaries_bp.route('/batch', methods=['POST'])
@jwt_required()
def batch_update_dictionaries():
    """批量更新字典项状态"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role != 'admin':
            return jsonify({'error': '权限不足'}), 403
        
        data = request.get_json()
        ids = data.get('ids', [])
        action = data.get('action')  # 'activate', 'deactivate', 'delete'
        
        if not ids or not action:
            return jsonify({'error': '参数不完整'}), 400
        
        if action == 'activate':
            query = text("""
                UPDATE system_dictionaries 
                SET is_active = 1, updated_at = :updated_at
                WHERE id IN :ids AND is_system = 0
            """)
        elif action == 'deactivate':
            query = text("""
                UPDATE system_dictionaries 
                SET is_active = 0, updated_at = :updated_at
                WHERE id IN :ids AND is_system = 0
            """)
        elif action == 'delete':
            query = text("""
                DELETE FROM system_dictionaries 
                WHERE id IN :ids AND is_system = 0
            """)
        else:
            return jsonify({'error': '无效的操作类型'}), 400
        
        # 将列表转换为元组以用于SQL IN子句
        ids_tuple = tuple(ids)
        params = {'ids': ids_tuple}
        
        if action != 'delete':
            params['updated_at'] = datetime.now()
        
        db.session.execute(query, params)
        db.session.commit()
        
        return jsonify({'message': f'批量{action}操作成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500